<template>
  <div class="task-reminder">
    <!-- 提醒设置和刷新 -->
    <div class="reminder-settings">
      <el-card>
        <div class="settings-header">
          <el-button type="text" @click="showSettings = true">
            <el-icon><Setting /></el-icon>
            提醒设置
          </el-button>
          <div class="refresh-section">
            <el-button 
              type="text" 
              :loading="loading" 
              @click="refreshData"
              size="small"
            >
              <el-icon v-if="!loading"><Refresh /></el-icon>
              刷新
            </el-button>
            <span v-if="lastUpdateTime" class="update-time">
              更新时间: {{ formatUpdateTime(lastUpdateTime) }}
            </span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 任务概览 -->
    <div class="task-overview">
      <el-row :gutter="10">
        <el-col
          v-for="task in taskSummary"
          :key="task.type"
          :span="12"
          @click="goToDetail(task.type, task.completionCycle)"
        >
          <el-card class="task-card" shadow="hover">
            <div class="task-progress">
              <el-progress
                type="circle"
                :percentage="task.completionRate"
                :width="60"
                :color="getProgressColor(task.completionRate)"
              >
                <template #default="{ percentage }">
                  <span class="progress-text">{{ percentage }}%</span>
                </template>
              </el-progress>
            </div>
            <div class="task-info">
              <div class="task-name">{{ task.name }}</div>
              <div class="task-count">
                <span class="completed">{{ task.completed }}</span>
                /
                <span class="total">{{ task.total }}</span>
              </div>
              <div class="task-deadline" v-if="task.deadline">
                <span class="deadline-label">截止：</span>
                <span class="deadline-text" :class="getDeadlineClass(task.daysRemaining)">
                  {{ formatTaskDeadline(task.deadline, task.daysRemaining) }}
                </span>
              </div>
              <el-tag :type="getStatusType(task)" size="small">
                {{ getStatusText(task) }}
              </el-tag>
              
              <!-- 智能评估详情 -->
              <div v-if="task.assessment" class="assessment-details">
                <div class="assessment-summary">{{ task.assessment.summary }}</div>
                <div class="comparison-info">
                  <span v-if="task.peerComparison && task.peerComparison.totalPeers > 1" class="peer-comparison">
                    团队排名: {{ task.peerComparison.ranking }}/{{ task.peerComparison.totalPeers }}
                    ({{ task.peerComparison.avgRate.toFixed(1) }}%平均)
                  </span>
                  <span v-if="task.historicalComparison && task.historicalComparison.trend !== 'no_history'" class="historical-comparison">
                    相比历史: 
                    <span :class="getTrendClass(task.historicalComparison.trend)">
                      {{ getTrendText(task.historicalComparison.trend) }}
                    </span>
                  </span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 紧急任务提醒 -->
    <div class="urgent-tasks" v-if="urgentTasks.length > 0">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>紧急任务</span>
          </div>
        </template>
        <el-timeline>
          <el-timeline-item
            v-for="task in urgentTasks"
            :key="task.id"
            :timestamp="task.deadline"
            placement="top"
            :type="getUrgentTaskType(task.reminderType)"
            @click="goToDetail(task.type, task.completionCycle)"
          >
            <el-card class="urgent-task-item" shadow="hover">
              <div class="task-header">
                <el-icon :color="getUrgentTaskColor(task.reminderType)">
                  <component :is="getUrgentTaskIcon(task.reminderType)" />
                </el-icon>
                <span class="task-title">{{ task.title }}</span>
                <el-tag :type="getUrgentTaskTagType(task.reminderType)" size="small">
                  {{ getUrgentTaskLabel(task.reminderType) }}
                </el-tag>
              </div>
              <p class="task-desc">{{ task.description }}</p>
              <div class="task-meta">
                <span class="uncompleted-count">未完成：{{ task.uncompletedCount }}户</span>
                <span class="days-info" v-if="task.daysUntilDeadline !== undefined">
                  {{ getDaysInfo(task.daysUntilDeadline) }}
                </span>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </el-card>
    </div>



    <!-- 设置弹窗 -->
    <el-dialog v-model="showSettings" title="提醒设置" width="90%">
      <div class="settings-content">
        <el-form :model="settings" label-width="120px">
          <el-form-item label="每周一提醒">
            <el-switch v-model="settings.weeklyReminder" />
          </el-form-item>
          <el-form-item label="截止前三天提醒">
            <el-switch v-model="settings.deadlineReminder" />
          </el-form-item>
          <el-form-item label="提醒时间">
            <el-time-picker
              v-model="reminderTime"
              format="HH:mm"
              value-format="HH:mm"
              placeholder="选择提醒时间"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSettings = false">取消</el-button>
          <el-button type="primary" @click="saveSettings">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElNotification } from 'element-plus'
import { Setting, Warning, Clock, Bell, CircleClose, Refresh } from '@element-plus/icons-vue'
import { trpc } from '@/utils/trpc'
import { AuthUtils } from '@/utils/auth'
import { dataCache, getCacheKey } from '@/utils/cache'
import { debounce, requestQueue } from '@/utils/debounce'

const router = useRouter()

// 响应式数据
const showSettings = ref(false)
const reminderTime = ref('09:00')
const loading = ref(false)
const lastUpdateTime = ref<string | null>(null)

// 设置数据
const settings = reactive({
  weeklyReminder: true,
  deadlineReminder: true,
  reminderTime: '09:00'
})

// 任务汇总（真实数据）
const taskSummary = ref<any[]>([])
// 紧急任务（真实数据）
const urgentTasks = ref<any[]>([])

// 计算属性和方法
const getProgressColor = (rate: number) => {
  if (rate >= 80) return '#67c23a'
  if (rate >= 60) return '#e6a23c'
  return '#f56c6c'
}

const getStatusType = (task: any) => {
  // 如果有智能评估数据，使用新的评估结果
  if (task.assessment) {
    const statusMap = {
      'excellent': 'success',
      'good': 'success', 
      'normal': 'info',
      'attention': 'warning',
      'behind': 'danger'
    }
    return statusMap[task.assessment.status] || 'info'
  }
  
  // 兜底逻辑：使用原有的简单判断
  const rate = task.completionRate || 0
  if (rate >= 80) return 'success'
  if (rate >= 60) return 'warning'
  return 'danger'
}

const getStatusText = (task: any) => {
  // 如果有智能评估数据，使用新的评估结果
  if (task.assessment) {
    const statusMap = {
      'excellent': '进度优秀',
      'good': '进度良好',
      'normal': '进度正常',
      'attention': '需要关注',
      'behind': '进度落后'
    }
    return statusMap[task.assessment.status] || '进度正常'
  }
  
  // 兜底逻辑：使用原有的简单判断
  const rate = task.completionRate || 0
  if (rate >= 80) return '进度良好'
  if (rate >= 60) return '需要关注'
  return '进度落后'
}

const getDeadlineClass = (daysRemaining: number) => {
  if (daysRemaining < 0) return 'overdue'
  if (daysRemaining <= 3) return 'urgent'
  if (daysRemaining <= 7) return 'warning'
  return 'normal'
}

const formatTaskDeadline = (deadline: string | Date, daysRemaining: number) => {
  const date = new Date(deadline)
  const dateStr = `${date.getMonth() + 1}月${date.getDate()}日`

  if (daysRemaining < 0) {
    return `${dateStr} (逾期${Math.abs(daysRemaining)}天)`
  } else if (daysRemaining === 0) {
    return `${dateStr} (今天)`
  } else if (daysRemaining <= 7) {
    return `${dateStr} (${daysRemaining}天后)`
  } else {
    return dateStr
  }
}

const getUrgentTaskType = (reminderType: string) => {
  switch (reminderType) {
    case 'overdue': return 'danger'
    case 'deadline': return 'warning'
    case 'weekly': return 'info'
    default: return 'primary'
  }
}

const getUrgentTaskColor = (reminderType: string) => {
  switch (reminderType) {
    case 'overdue': return '#f56c6c'
    case 'deadline': return '#e6a23c'
    case 'weekly': return '#409eff'
    default: return '#909399'
  }
}

const getUrgentTaskIcon = (reminderType: string) => {
  switch (reminderType) {
    case 'overdue': return CircleClose
    case 'deadline': return Warning
    case 'weekly': return Bell
    default: return Clock
  }
}

const getUrgentTaskTagType = (reminderType: string) => {
  switch (reminderType) {
    case 'overdue': return 'danger'
    case 'deadline': return 'warning'
    case 'weekly': return 'info'
    default: return ''
  }
}

const getUrgentTaskLabel = (reminderType: string) => {
  switch (reminderType) {
    case 'overdue': return '已逾期'
    case 'deadline': return '即将截止'
    case 'weekly': return '周一提醒'
    default: return '提醒'
  }
}

const getDaysInfo = (daysUntilDeadline: number) => {
  if (daysUntilDeadline < 0) {
    return `逾期${Math.abs(daysUntilDeadline)}天`
  } else if (daysUntilDeadline === 0) {
    return '今天截止'
  } else if (daysUntilDeadline <= 3) {
    return `${daysUntilDeadline}天后截止`
  } else {
    return `${daysUntilDeadline}天后截止`
  }
}

const goToDetail = (type: string, completionCycle?: string) => {
  const routeMap: Record<string, string> = {
    'client-visit': '/client-visit',
    'integrity-building': '/integrity-building',
    'client-evaluation': '/client-evaluation',
    'satisfaction-survey': '/satisfaction-survey',
    'team-collaboration': '/team-collaboration'
  }
  const periodMap: Record<string, string> = {
    monthly: 'month',
    quarterly: 'quarter',
    yearly: 'year'
  }
  const query: any = { filter: 'uncompleted' }
  if (completionCycle && periodMap[completionCycle]) {
    query.period = periodMap[completionCycle]
  }
  if (routeMap[type]) {
    router.push({ path: routeMap[type], query })
  }
}

const saveSettings = async () => {
  try {
    const user = AuthUtils.getUser<any>()
    if (!user?.id) {
      ElMessage.error('用户未登录')
      return
    }

    await trpc.reminder.saveSettings.mutate({
      managerId: user.id,
      weeklyReminder: settings.weeklyReminder,
      deadlineReminder: settings.deadlineReminder,
      reminderTime: reminderTime.value
    })

    settings.reminderTime = reminderTime.value
    
    // 清除设置缓存，下次重新获取
    const cacheKey = getCacheKey.reminderSettings(user.id)
    dataCache.delete(cacheKey)
    
    // 强制刷新任务数据，因为设置可能影响提醒逻辑
    debouncedLoadTaskData(true)
    
    ElMessage.success('设置已保存')
    showSettings.value = false
  } catch (error) {
    console.error('保存设置失败:', error)
    ElMessage.error('保存设置失败')
  }
}

// 防抖的数据加载函数
const debouncedLoadTaskData = debounce(async (forceRefresh = false) => {
  await loadTaskData(forceRefresh)
}, 500)

// 生命周期
onMounted(() => {
  loadTaskData()
  loadReminderSettings()
  
  // 延迟检查提醒，避免与数据加载冲突
  setTimeout(() => {
    checkReminders()
  }, 1000)
})

onUnmounted(() => {
  // 清理待处理的请求
  requestQueue.clear()
})

// 加载用户提醒设置
const loadReminderSettings = async () => {
  try {
    const user = AuthUtils.getUser<any>()
    if (!user?.id) return

    const cacheKey = getCacheKey.reminderSettings(user.id)
    
    // 尝试从缓存获取
    if (dataCache.has(cacheKey)) {
      const cachedSettings = dataCache.get(cacheKey)
      if (cachedSettings) {
        updateSettingsUI(cachedSettings)
        return
      }
    }

    const response = await trpc.reminder.getSettings.query({ managerId: user.id })
    if (response?.success && response.data) {
      const userSettings = response.data
      // 缓存设置（10分钟有效期）
      dataCache.set(cacheKey, userSettings, 10 * 60 * 1000)
      updateSettingsUI(userSettings)
    }
  } catch (error) {
    console.error('加载提醒设置失败:', error)
  }
}

const updateSettingsUI = (userSettings: any) => {
  settings.weeklyReminder = userSettings.weeklyReminder
  settings.deadlineReminder = userSettings.deadlineReminder
  settings.reminderTime = userSettings.reminderTime
  reminderTime.value = userSettings.reminderTime
}

const loadTaskData = async (forceRefresh = false) => {
  try {
    const user = AuthUtils.getUser<any>()
    if (!user?.id) return

    loading.value = true
    const cacheKey = getCacheKey.taskDashboard(user.id, false)
    
    // 尝试从缓存获取数据（除非强制刷新）
    if (!forceRefresh && dataCache.has(cacheKey)) {
      const cachedData = dataCache.get(cacheKey)
      if (cachedData) {
        updateUIWithData(cachedData)
        loading.value = false
        return
      }
    }

    // 使用请求队列防止重复请求
    const data = await requestQueue.execute(cacheKey, async () => {
      return await trpc.reminder.dashboard.query({ 
        managerId: user.id,
        includeProgressComparison: false // 默认不包含复杂的对比数据，提升性能
      })
    })

    if (data?.success) {
      // 缓存结果（3分钟有效期）
      dataCache.set(cacheKey, data.data, 3 * 60 * 1000)
      updateUIWithData(data.data)
      lastUpdateTime.value = new Date().toISOString()
    } else {
      throw new Error(data?.message || '获取任务数据失败')
    }
  } catch (error) {
    console.error('加载任务数据失败:', error)
    ElMessage.error('加载任务提醒失败')
  } finally {
    loading.value = false
  }
}

const updateUIWithData = (data: any) => {
  // 更新任务汇总
  taskSummary.value = (data.taskSummary || []).map((task: any) => ({
    type: mapServiceType(task.serviceName),
    name: task.serviceName,
    completed: task.completedCount,
    total: task.totalClients,
    completionRate: task.progressPercentage,
    completionCycle: task.completionCycle,
    deadline: task.deadline,
    daysRemaining: task.daysRemaining,
    assessment: task.assessment,
    peerComparison: task.peerComparison,
    historicalComparison: task.historicalComparison
  }))

  // 更新紧急任务
  urgentTasks.value = (data.reminders || [])
    .filter((s: any) => s.uncompletedCount > 0 && (s.reminderType === 'weekly' || s.reminderType === 'deadline' || s.reminderType === 'overdue'))
    .map((s: any, idx: number) => ({
      id: idx + 1,
      type: mapServiceType(s.serviceName),
      title: s.serviceName,
      description: s.reminderMessage,
      deadline: formatDeadline(s.deadline),
      daysUntilDeadline: s.daysUntilDeadline,
      reminderType: s.reminderType,
      completionCycle: s.completionCycle,
      uncompletedCount: s.uncompletedCount
    }))
}

const checkReminders = async () => {
  // 后端已做“每周一/截止前三天”判断（基于用户设置），这里只做前端通知
  if (urgentTasks.value.length > 0) {
    const mostUrgentTask = urgentTasks.value.find(task => task.reminderType === 'overdue') ||
                          urgentTasks.value.find(task => task.reminderType === 'deadline') ||
                          urgentTasks.value[0]

    const notificationType = mostUrgentTask.reminderType === 'overdue' ? 'error' :
                           mostUrgentTask.reminderType === 'deadline' ? 'warning' : 'info'

    ElNotification({
      title: `任务提醒 - ${getUrgentTaskLabel(mostUrgentTask.reminderType)}`,
      message: mostUrgentTask.description,
      type: notificationType,
      duration: 5000,
      onClick: () => {
        goToDetail(mostUrgentTask.type, mostUrgentTask.completionCycle)
      }
    })
  }
}

const formatDeadline = (deadline: string | Date) => {
  const date = new Date(deadline)
  const now = new Date()
  const diffTime = date.getTime() - now.getTime()
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

  const dateStr = `${date.getMonth() + 1}月${date.getDate()}日`

  if (diffDays < 0) {
    return `${dateStr} (已逾期${Math.abs(diffDays)}天)`
  } else if (diffDays === 0) {
    return `${dateStr} (今天截止)`
  } else if (diffDays <= 3) {
    return `${dateStr} (还有${diffDays}天)`
  } else {
    return dateStr
  }
}

function mapServiceType(serviceName: string): string {
  if (serviceName.includes('拜访')) return 'client-visit'
  if (serviceName.includes('诚信') || serviceName.includes('五化')) return 'integrity-building'
  if (serviceName.includes('评价')) return 'client-evaluation'
  if (serviceName.includes('满意')) return 'satisfaction-survey'
  if (serviceName.includes('协同')) return 'team-collaboration'
  return 'client-visit'
}

const getTrendText = (trend: string) => {
  switch (trend) {
    case 'improving': return '提升'
    case 'stable': return '持平'
    case 'declining': return '下降'
    default: return '持平'
  }
}

const getTrendClass = (trend: string) => {
  switch (trend) {
    case 'improving': return 'trend-improving'
    case 'stable': return 'trend-stable'
    case 'declining': return 'trend-declining'
    default: return 'trend-stable'
  }
}

// 刷新数据
const refreshData = () => {
  debouncedLoadTaskData(true)
}

// 格式化更新时间
const formatUpdateTime = (timestamp: string) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = Math.floor((now.getTime() - date.getTime()) / 1000)
  
  if (diff < 60) return '刚刚'
  if (diff < 3600) return `${Math.floor(diff / 60)}分钟前`
  if (diff < 86400) return `${Math.floor(diff / 3600)}小时前`
  return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 按需加载智能评估数据
const loadProgressComparison = async (serviceId: number) => {
  try {
    const user = AuthUtils.getUser<any>()
    if (!user?.id) return null

    const cacheKey = getCacheKey.progressComparison(user.id, serviceId)
    
    // 检查缓存
    if (dataCache.has(cacheKey)) {
      return dataCache.get(cacheKey)
    }

    // 发起请求
    const response = await trpc.reminder.progressComparison.query({
      managerId: user.id,
      serviceId
    })

    if (response?.success) {
      // 缓存结果（5分钟）
      dataCache.set(cacheKey, response.data, 5 * 60 * 1000)
      return response.data
    }

    return null
  } catch (error) {
    console.warn(`获取服务 ${serviceId} 的智能评估失败:`, error)
    return null
  }
}
</script>

<style scoped>
.task-reminder {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20px;
}

.reminder-settings {
  margin-bottom: 20px;
}

.settings-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.refresh-section {
  display: flex;
  align-items: center;
  gap: 10px;
}

.update-time {
  font-size: 12px;
  color: #999;
}

.task-overview {
  margin-bottom: 20px;
}

.task-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.task-card:hover {
  transform: translateY(-2px);
}

.task-progress {
  margin-bottom: 15px;
}

.progress-text {
  font-size: 12px;
  font-weight: bold;
  color: #333;
}

.task-info {
  text-align: center;
  width: 100%;
}

.task-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.task-count {
  font-size: 14px;
  margin-bottom: 8px;
}

.task-deadline {
  font-size: 12px;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.deadline-label {
  color: #666;
  margin-right: 4px;
}

.deadline-text {
  font-weight: bold;
}

.deadline-text.normal {
  color: #666;
}

.deadline-text.warning {
  color: #e6a23c;
}

.deadline-text.urgent {
  color: #f56c6c;
}

.deadline-text.overdue {
  color: #f56c6c;
  text-decoration: line-through;
}

.completed {
  color: #67c23a;
  font-weight: bold;
}

.total {
  color: #666;
}

.urgent-tasks {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: bold;
}

.urgent-task-item {
  cursor: pointer;
  transition: all 0.3s;
}

.urgent-task-item:hover {
  transform: translateY(-2px);
}

.task-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.task-title {
  margin-left: 8px;
  font-weight: bold;
  flex: 1;
}

.task-desc {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 14px;
}

.task-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.uncompleted-count {
  color: #f56c6c;
  font-weight: bold;
}

.days-info {
  color: #e6a23c;
  font-weight: bold;
}

/* 智能评估详情样式 */
.assessment-details {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
  font-size: 11px;
}

.assessment-summary {
  color: #666;
  margin-bottom: 4px;
  line-height: 1.3;
}

.comparison-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.peer-comparison,
.historical-comparison {
  color: #999;
  font-size: 10px;
}

.trend-improving {
  color: #67c23a;
  font-weight: bold;
}

.trend-stable {
  color: #409eff;
  font-weight: bold;
}

.trend-declining {
  color: #f56c6c;
  font-weight: bold;
}



.settings-content {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
